﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WFSocket
{
    public partial class Form1 : Form
    {
        /// <summary>
        /// 用来存放连接服务的客户端的IP地址和端口号，对应的Socket
        /// </summary>
        Dictionary<string, Socket> dicSocket = new Dictionary<string, Socket>();

        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 初期化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
            //不检测跨线程之间的空间调用
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        /// <summary>
        /// 开始监听按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnListen_Click(object sender, EventArgs e)
        {
            try
            {
                //当点击开始监听的时候 在服务器端创建一个负责监IP地址跟端口号的Socket
                Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                //获取IP
                //IPAddress ip = IPAddress.Any;
                //服务器IP地址 
                //********************************
                //要添加IP合法性检测
                //TODO
                //********************************

                IPAddress ip = IPAddress.Parse(ipAddress.Text.Trim());

                //创建端口号
                IPEndPoint port = new IPEndPoint(ip, Convert.ToInt32(serverPort.Text.Trim()));

                //监听
                socketWatch.Bind(port);

                ShowMsg("监听成功");

                //********************************
                //监听成功后按钮要非活性，不可再点击
                //TODO
                //********************************

                //设定最多10个排队连接请求 
                socketWatch.Listen(10);

                //新建线程，去接收客户端发来的信息
                Thread td = new Thread(AcceptClientMgs);
                td.IsBackground = true;
                td.Start(socketWatch);
            }
            catch (Exception)
            {              
                throw;
            }
        }

        /// <summary>
        /// 接收客户端发送的信息
        /// </summary>
        /// <param name="o"></param>
        private void AcceptClientMgs(object o)
        {
            try
            {
                Socket socketWatc = (Socket)o;
                while (true)
                {
                    ////负责跟客户端通信的Socket
                    Socket socketSend = socketWatc.Accept();

                    //将远程连接的客户端的IP地址和Socket存入集合中
                    dicSocket.Add(socketSend.RemoteEndPoint.ToString(), socketSend);

                    ShowMsg(socketSend.RemoteEndPoint.ToString() + ": 连接成功");

                    //新建线程循环接收客户端发来的信息
                    Thread td = new Thread(Recive);
                    td.IsBackground = true;
                    td.Start(socketSend);
                }
            }
            catch { }

        }

        /// <summary>
        /// 接收客户端发来的数据，并显示出来
        /// </summary>
        private void Recive(object o)
        {
            Socket socketSend = (Socket)o;
            try
            {
                while (true)
                {
                    //客户端连接成功后，服务器应该接受客户端发来的消息

                    if (socketSend == null)
                    {
                        ShowMsg("客户端没有发送信息。");
                        continue;
                    }

                    byte[] buffer = new byte[1024 * 1024 * 2];
                    //实际接受到的有效字节数
                    int r = socketSend.Receive(buffer);
                    //如果客户端关闭，发送的数据就为空，然后就跳出循环
                    if (r == 0)
                    {
                        break;
                    }

                    //接收客户端信息
                    string strMsg = Encoding.UTF8.GetString(buffer, 0, r);

                    byte[] acceptbuffer = Encoding.UTF8.GetBytes("服务器端接收成功");

                    //将字节数组传递给客户端
                    socketSend.Send(acceptbuffer);

                    ShowMsg(socketSend.RemoteEndPoint.ToString() + ": " + strMsg);
                }
            }
            catch { }
        }

        /// <summary>
        /// 显示信息
        /// </summary>
        /// <param name="message"></param>
        private void ShowMsg(string message)
        {
            serverMessage.AppendText(message + "\r\n");
        }
       
    }
}
